import sys
import os
import codecs
import markdown

MK_TEMPLATE_DIR = "J:\\ide\\vim\\mkd"
MK_TEMPLATE_FILE = MK_TEMPLATE_DIR + os.sep + 'template.htm'
MK_TEMPLATE_EXT=["style.css"]

def copy_file(src, dest):
    if os.path.exists(src):
        src_file = open(src, 'r')
        dest_file = open(dest, 'w')
        dest_file.write(src_file.read())
        src_file.close()
        dest_file.close()

if __name__ == '__main__':
    if len(sys.argv) > 1:
        #mkdir
        file_name = os.path.splitext(sys.argv[1])[0]
        target_dir = os.getcwd() + os.sep + file_name
        if not os.path.isdir(target_dir):
            os.mkdir(target_dir)
        #source
        src_file = codecs.open(sys.argv[1], "r", "gbk")
        result = markdown.markdown(src_file.read(), ["toc", "tables", "codehilite"])
        src_file.close()
        #template
        temp_file = open(MK_TEMPLATE_FILE, "r")
        template = temp_file.read()
        temp_file.close()
        #destination
        dest_file = codecs.open(target_dir + os.sep + "index.htm", "w", "utf8")
        dest_file.write(template % (os.path.basename(sys.argv[1]), result))
        dest_file.close()
        #copy
        for ext_file in MK_TEMPLATE_EXT:
            copy_file(MK_TEMPLATE_DIR + os.sep + ext_file, target_dir + os.sep + ext_file)
    else:
        raise RuntimeError("Usage: mk.py inputfile")
